import { createRouter, createWebHistory } from 'vue-router';
import { Toast } from 'vant';
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: "/home"
        },
        //404路由
        { path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: () => import('../views/notfound.vue')
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('../views/home.vue')
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/login.vue')
        },
        {
            path: '/user',
            name: 'user',
            component: () => import('../views/user.vue')
        },
        {
            path: '/register',
            name: 'register',
            redirect: "/register/step1",
            component: () => import('../views/register/register.vue'),
            children: [
                {
                    path: 'step1',
                    name: 'step1',
                    component: () => import('../views/register/step1.vue')
                },
                {
                    path: 'step2',
                    name: 'step2',
                    component: () => import('../views/register/step2.vue')
                },
                {
                    path: 'step3',
                    name: 'step3',
                    component: () => import('../views/register/step3.vue')
                },
            ]
        },
        {
            path: '/cart',
            name: 'cart',
            component: () => import('../views/cart.vue')
        },
        {
            path: '/adress',
            name: 'adress',
            component: () => import('../views/adress.vue')
        },
        {
            path: '/order',
            name: 'order',
            component: () => import('../views/order.vue')
        },
        {
            path: '/search',
            name: 'search',
            component: () => import('../views/search.vue')
        },
        {
            path: '/detail',
            name: 'detail',
            component: () => import('../views/detail.vue')
        },
    ]
});
// 路由前置守卫
router.beforeEach((to, from) => {
    // 有token就表示已经登录
    // 想要进入购物车页面，必须有登录标识token
    let token = localStorage.getItem('token');
    if (to.path == '/cart') {
        // 此时必须要有token
        if (token) {
            return true;
        }
        else {
            Toast('请先登录');
            return { path: '/login' }; // 强制去到登录页
        }
    }
    else {
        // 如果不是去往购物车的路由，则直接通过守卫，去到to所对应的路由界面
        return true;
    }
});
export default router;
